from flask import (
    Blueprint,
    request,
    g,
    render_template,
)

from exit import db
from .decorators import login_need
from flask_paginate import Pagination, get_page_parameter
from apps.mall.models import *
from .models import CMSRecord
from .forms import *
from apps.mall.forms import DetailForm
from apps.common.models import *
from utils import restful, common_util, api_util, tree
from datetime import datetime
from apps.api.models import *
import requests
import json
from .views_cms import bp
from sqlalchemy import or_
import ast
from decimal import Decimal


@bp.route('/mall/article_manage/')     # 类型管理
@login_need
def article_manage():
    status = request.args.get('status')
    return render_template('cms_mall/article.html')


@bp.route('/mall/article_info/')     # 文章信息
@login_need
def article_info():
    type_id = request.args.get('type_id')
    filters = list()
    if type_id:
        filters.append(Article.type_id == type_id)
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    type_obj = Article.query.filter(*filters).order_by(Article.create_time.desc())

    types = type_obj.slice(start, end)
    total = type_obj.count()
    category_list = list()
    for i in types:
        type_json = i.article_json()
        category_list.append(type_json)
    return restful.table_success(data=category_list, count=total)


@bp.route('/mall/update_article/', methods=['POST'])     # 更新文章
@login_need
def update_article():
    form = UpdateArticleForm(request.form)
    if form.validate():
        title = form.title.data
        # content = form.content.data
        article_img = form.article_img.data
        # author = form.author.data
        article_time = form.article_time.data
        article_id = form.article_id.data

        try:
            article_date = datetime.strptime(article_time, '%Y-%m-%d').date()
        except Exception as e:
            print(e)
            return restful.params_error(message='日期格式错误')

        article = Article.query.filter_by(id=article_id).first()
        if article is None:
            create_article = Article(
                title=title, content=None, author=None,
                article_time=article_date,
                article_img=article_img
            )
            db.session.add(create_article)
            record = '添加 <{}> 文章'.format(title)
        else:
            article.title = title
            # article.content = content
            article.article_img = article_img
            # article.type_id = article_type.id
            # article.author = author
            article.article_time = article_date
            # article.works = works
            # goods_type.big_img = big_img
            record = '更新 <{}> 文章'.format(article.title)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/mall/del_article/', methods=['POST'])    # 删除文章
@login_need
def del_article():
    article_id = request.form.get('article_id')
    article = Article.query.filter_by(id=article_id).first()
    if article is None:
        return restful.params_error(message='未找到数据')
    record = '删除 <{}> 文章'.format(article.title)
    db.session.delete(article)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()

